package cn.dengta.webapp.trade.dao;

import java.util.Date;
import java.util.List;

import cn.dengta.webapp.base.dao.BaseDao;
import cn.dengta.webapp.trade.entity.UserEquityBag;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import org.apache.ibatis.annotations.*;

/**
 * 用户权益包 Mapper 接口
 *
 * @author xy
 * @since 2022-08-04
 */
public interface UserEquityBagDao extends BaseDao<UserEquityBag> {

	@Select("SELECT * FROM im_user_equity_bag WHERE user_id = #{userId} AND type = #{type} AND remain > 0 AND expire_time >= NOW() ORDER BY expire_time, id LIMIT 100")
	List<UserEquityBag> findByUserAndType(@Param("userId") Long userId, @Param("type") Integer type);

	@Select("SELECT * FROM im_user_equity_bag WHERE user_id = #{userId} AND type = #{type} AND remain > 0 AND expire_time >= NOW() ORDER BY expire_time, id LIMIT 1")
	UserEquityBag findFirstByUserAndType(@Param("userId") Long userId, @Param("type") Integer type);

	@Select("SELECT SUM(remain) FROM im_user_equity_bag WHERE user_id = #{userId} AND type = #{type} AND remain > 0 AND expire_time >= #{startTime}")
	Integer getTotalRemainByType(@Param("userId") Long userId, @Param("type") Integer type, @Param("startTime") Date startTime);

	@Select("SELECT id, remain FROM im_user_equity_bag WHERE user_id = #{userId} AND type = #{type} AND remain > 0 AND expire_time >= #{startTime} ORDER BY expire_time")
	List<UserEquityBag> findRemainByType(@Param("userId") Long userId, @Param("type") Integer type, @Param("startTime") Date startTime);

	@Update("UPDATE im_user_equity_bag SET remain = remain - #{used}, update_time = NOW(3) WHERE id = #{id} AND remain >= #{used}")
	int reduceRemain(@Param("id") Long id, @Param("used") Integer used);

	@Update("UPDATE im_user_equity_bag SET remain = remain - #{count}  WHERE id = #{id} AND user_id = #{userId} AND type = 3 AND remain >= #{count}")
	int updateByTypeAndId(@Param("id") Long id, @Param("userId") Long userId, @Param("count") Integer count);

	@Update("UPDATE im_user_equity_bag SET remain = remain + #{count}, total = total + #{count}, expire_time = #{expireTime}  WHERE id = #{id}")
	int addTotal(@Param("id") Long id, @Param("count") Integer count, @Param("expireTime") Date expireTime);

	@Select("SELECT log.* FROM im_user_equity_bag log JOIN im_user_bag_avatar a ON log.period = a.id ${ew.customSqlSegment}")
	List<UserEquityBag> findByAlias(@Param("ew") Wrapper<UserEquityBag> wrapper);

}
